package list;

import java.util.HashMap;
import java.util.Map;

/**
 * @author macy
 * @date 2025/5/14 14:48
 */
public class SlidWindow {

    /**
     * 最长无重复子串
     * @param s
     * @return
     */
    public static int lengthOfLongestSubstring(String s) {
        Map<Character, Integer> window = new HashMap<>();
        // 滑动窗口左指针
        int left = 0;
        // 最大长度
        int maxLength = 0;

        for (int right = 0; right < s.length(); right++) {
            char ch = s.charAt(right);

            // 如果字符已存在，并且其索引大于等于 left，则更新 left
            //为啥要+1,而不是仅=win.get(ch)，滑动窗口是不能包含重复字符的

            if (window.containsKey(ch) && window.get(ch) >= left) {
                left = window.get(ch) + 1;
            }
            // 更新当前字符的位置
            window.put(ch, right);
            // 计算窗口大小
            maxLength = Math.max(maxLength, right - left + 1);
        }

        return maxLength;
    }

    public static int lengthOfLongestSubstring1(String s) {
        int left = 0, right = 0;
        int ans=1;
        HashMap<Character, Integer> map = new HashMap<>();

        while (right < s.length()){
            char c = s.charAt(right);
            if(map.containsKey(c)){
                left=map.get(c)+1;
            }
            map.put(c,right);
            ans=Math.max(ans,right-left+1);
            right++;
        }
        return ans;

    }

    public static void main(String[] args) {
        System.out.println("Hello, World!");
        HashMap<Integer, Integer> map = new HashMap<>();

        map.put(1, 1);
        map.put(1, 2);
        System.out.println(map.get(1));
        String s="eqwtabcabcbb";
        System.out.println(lengthOfLongestSubstring1(s));

    }

}
